Component({
  /**
   * 组件的属性列表
   */
  properties: {
    nowPop: {
      type: String
    },
    detailData: {
      type: Object,
      value: {
        img: "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1301561917,1696120670&fm=26&gp=0.jpg",
        price: "39.00",
      }
    },
    boxH: {
      type: Number,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    count: 1,
    disable: true,
    animationData: {},
    sku: {},
    skuDict: {},
    skuObject: {},
    defaultList: {},
    defLength: 0,
    defaulKey: "",
    chooseAbleData: {},
    chooseCount: 0,
    count: 1,
  },

  /**
   * 组件的方法列表
   */
  methods: {
     // 点x关闭
     close(){
      console.log(111);
      this.triggerEvent('myevent',false)
    },
    // 减少数量
    countSub() {
      let count = this.data.count
      count = count > 1 ? count - 1 : count
      let disable = count == 1 ? true : false
      this.setData({
        count,
        disable
      })
    },
    // 增加数量
    countAdd() {
      let count = this.data.count;
      count++;
      this.setData({
        count
      })
    },
    // 输入数量
    inputCount(e) {
      let count = e.detail.value;
      count = Number.isNaN(Number(count)) ? "" : count === "" ? count : count < 1 ? 1 : count
      let disable = count == 1 ? true : false
      this.setData({
        count,
        disable
      })
    },

    // 筛选数据
    screen(option) {
      // 查询到的数据
      let searched = {}

      let skuDict = Object.keys(this.data.skuDict)
      // 遍历选项
      console.log(skuDict)
      skuDict.forEach(item => {
        let tmp = {}
        skuDict.forEach(i => {
          if (item !== i) {
            // 判断此项有无筛选条件
            console.log(item,i)
            if (option[i]) {

              tmp[i] = option[i]
            }
          }
        })
        let searchedData = this.searchData(this, tmp)
        let chooseAble = dealData(searchedData, item)
        searched[item] = chooseAble
      })
      this.setData({
        chooseAbleData: searched
      })

      // 处理数据
      function dealData(data, curr) {
        let tmp = []
        data.forEach(item => {
          // console.log(item)
          if (!tmp.includes(item.optional[curr])) {
            tmp.push(item.optional[curr])
          }
        })
        return tmp
      }
      return searched
    },
    // 查询数据
    searchData(self, option) {
      // 遍历数据源
      let searched = []
      self.data.sku.forEach(item => {

        let count = 0
        let length = 0
        // 遍历筛选条件
        for (let i in option) {
          if (option.hasOwnProperty(i)) {
            // 计算筛选条件个数
            length++
            if (option[i] === item.optional[i]) {
              // 记录此条数据中满足筛选条件的元素个数
              count++
            }
          }
        }
        // 当count == lenght ，此条数据满足全部的筛选条件
        if (count === length && item.inventory != 0) {
          // 添加数据
          searched.push(item)
        }
      })
      return searched
    },

    // 判断数量是否为0
    isNull(e) {
      let count = e.detail.value;
      count = count === "" ? 1 : count
      let disable = count == 1 ? true : false
      this.setData({
        count,
        disable
      })
    },
    preventdefault() {

    },

    // 组件slideDown
    closePop() {
      let animation = wx.createAnimation({
        duration: 300
      })
      animation.height(0).opacity(0).step()
      this.setData({
        animationData: animation.export()
      })
    },

    // 计算可选属性
    computedChooseAble(searchData, tapData) {
      let chooseAbleData = {}
      // 设置可选对象数据格式 -->对象,其中每一个元素都为一个数据
      if (searchData[0]) {
        Object.keys(searchData[0].optional).forEach(item => chooseAbleData[item] = [])
      }
      // 遍历查询数据
      searchData.forEach(item => {
        // 遍历每条查询数据的可选对象
        for (let i in item.optional) {
          if (item.optional.hasOwnProperty(i)) {
            // 当可选项没有此项时，添加到对应的可选项列表
            if (!chooseAbleData[i].includes(item.optional[i])) {
              chooseAbleData[i].push(item.optional[i])
            }
          }
        }
      })
      this.setData({
        chooseAbleData
      })
    },
    // 点击确定按钮
    joinCar() {
      // 添加到购物车
      let goodID = this.data.detailData.goodID
      let num = this.data.count
      let price = ''
      let money = 0
      let sku = JSON.stringify(this.searchData(this,this.data.defaultList))
      let that = this

      if(this.data.defaultChooses == undefined){
        wx.showToast({
          title: '请选择商品属性',
          icon: 'none'
        })
      }else{
        price = Number(this.data.defaultChooses.price)
        money = num * price

        let getToken = new Promise((resolve) => {
          wx.getStorage({
            key: 'token',
            success(res) {
              console.log(res);
              resolve(res.data)
            }
          })
        }).then(
          res => {
            console.log(res);
            new Promise((resolve, reject) => {
              wx.request({
                url: 'http://api_dev.wanxikeji.cn/api/shoppingCarAddModify',
                method: "POST",
                header: {
                  'content-type': 'application/json,charset=utf8' // 默认值
                },
                data: {
                  token: res,
                  good_id: goodID,
                  num,
                  price,
                  money,
                  sku
                },
                success(res) {
                  console.log(res);
                  resolve(res.data)
                }
              })
            }).then(res => {
              console.log(res);
              if (res.code == 2000) {
                if(that.data.detailData.state == 1){
                  wx.showToast({
                    title: '添加成功',
                    icon: 'success'
                  })
                  var count = ++that.data.detailData.shopCount

                  if(count>9){
                    that.data.detailData.showCount = '9+'
                  }else{
                    that.data.detailData.showCount = count
                  }
                  console.log(that);

                  that.setData({
                    ['detailData.shopCount']: count,
                    ['detailData.showCount']: that.data.detailData.showCount,
                  })
                  this.triggerEvent('myevent',true)
                }else{
                  wx.navigateTo({
                    url: '../shopping_Cart/shopping_Cart?def='+true,
                  })
                }
              }
              else{
                wx.showToast({
                  title: '请登录',
                  icon:''
                })
              }
            }, err => {
              console.log(err)
            })
          }
        )
      }
      
    },


    // 选择配置
    chooseConfig(e) {
      // 获取点击的选项名，和选项值
      let {
        choosed,
        taped
      } = e.currentTarget.dataset
      // 获取筛选条件
      let defaultList = JSON.parse(JSON.stringify(this.data.defaultList))
      // 切换筛选条件
      if (defaultList[choosed] === taped) {
        // 选中时点击，清除当前筛选条件
        delete defaultList[choosed]
      } else {
        // 没选中时点击,添加筛选条件
        defaultList[choosed] = taped
      }
      // 通过筛选条件查询数据
      let searchData = this.screen(defaultList)

      // 通过查询到的数据设置可选项
      // this.computedChooseAble(searchData, choosed)
      // 查询对应价格
      let key = ""
      for (let i in this.data.sku[0].optional) {
        if (this.data.sku[0].optional.hasOwnProperty(i)) {
          key += defaultList[i]
        }
      }
      let defaultChooses = this.data.skuObject[key]

      this.setData({
        searchData,
        defaultList,
        defaultChooses
      })
    }
  },
  ready() {
    // 获取sku列表
    let sku = this.data.detailData.edition
    let skuDict = {}
    let skuObject = {}
    let defaultList = {}
    let chooseCount = 0
    
    // 获取可选项
    Object.keys(sku[0].optional).forEach(item => {
      chooseCount++
      skuDict[item] = []
    })
    sku.forEach(item => {
      let key = ""
      for (let i in item.optional) {
        if (item.optional.hasOwnProperty(i)) {
          key += item.optional[i]
          if (!skuDict[i].includes(item.optional[i])) {
            skuDict[i].push(item.optional[i])
          }
        }
      }
      skuObject[key] = item.generated
    })
    this.computedChooseAble(sku)
    console.log(this.data.chooseAbleData)
    this.setData({
      sku, // 数据源
      skuDict, // 数据源组成的可选项
      skuObject, // sku字段拼接起来的key和对应可变项组成的对象
      defaultList, // 选中的信息对象
      chooseCount,
    })

    // 组件slideUp
    let animation = wx.createAnimation({
      duration: 300
    })
    animation.height('1000rpx').opacity(1).step()
    this.setData({
      animationData: animation.export()
    })
  },
  observers: {
    'defaultList': function (val) {
      this.setData({
        // 获取选中信息的长度
        defLength: Object.keys(val).length
      })
    }
  }
})